﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace PKEngine
{
	/// <summary>
	/// Singleton that handles the loading of binary font.
	/// </summary>
	public class PKBinFontCache
	{
		#region Private Fields
		private Dictionary<string, WeakReference> cachedFonts;
		#endregion

		#region Singleton
		private static PKBinFontCache _sharedFontCache;

		public static PKBinFontCache SharedFontCache
		{
			get
			{
				if (_sharedFontCache == null)
				{
					_sharedFontCache = new PKBinFontCache();
				}
				return _sharedFontCache;
			}
		}
		#endregion

		#region Initialization
		private PKBinFontCache()
		{
			cachedFonts = new Dictionary<string, WeakReference>();
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Adds a font.
		/// </summary>
		/// <param name="filePath">The path of font file</param>
		/// <returns>Cached font</returns>
		public PKBinFont AddFont(string filePath)
		{
			Debug.Assert(!string.IsNullOrEmpty(filePath), "PKBinFontCache.AddFont: Argument cannot be null.");
			Debug.Assert(File.Exists(filePath), "PKBinFontCache.AddFont: Cannot find file.");

			string fileName = filePath.ToLower();
			PKBinFont font = GetFont(fileName);
			if (font == null)
			{
				string fileExt = Path.GetExtension(filePath).ToLower();
				if (fileExt == ".pkbf")
				{
					font = new PKBinFont(filePath);
					if (font != null)
					{
						cachedFonts.Add(fileName, new WeakReference(font));
					}
				}
			}

			return font;
		}

		/// <summary>
		/// Gets a font by key.
		/// </summary>
		/// <param name="key">The key</param>
		/// <returns>The font</returns>
		public PKBinFont GetFont(string key)
		{
			if (cachedFonts.ContainsKey(key))
			{
				WeakReference pFont = cachedFonts[key];
				if (!pFont.IsAlive)
				{
					cachedFonts.Remove(key);
					return null;
				}
				else
				{
					return pFont.Target as PKBinFont;
				}
			}
			return null;
		}

		/// <summary>
		/// Removes a cached font.
		/// </summary>
		/// <param name="font">Target font</param>
		public void RemoveFont(PKBinFont font)
		{
			if (font == null)
			{
				return;
			}

			foreach (KeyValuePair<string, WeakReference> kvPair in cachedFonts)
			{
				if (kvPair.Value.IsAlive && kvPair.Value.Target == font)
				{
					cachedFonts.Remove(kvPair.Key);
					break;
				}
			}
		}

		/// <summary>
		/// Removes a cached font.
		/// </summary>
		/// <param name="key">Target key</param>
		public void RemoveFont(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				return;
			}

			cachedFonts.Remove(key);
		}

		/// <summary>
		/// Clears all unused fonts.
		/// </summary>
		public void ClearUnusedFonts()
		{
			List<string> toRemoveList = new List<string>();
			foreach (KeyValuePair<string, WeakReference> kvPair in cachedFonts)
			{
				if (!kvPair.Value.IsAlive)
				{
					toRemoveList.Add(kvPair.Key);
				}
			}
			foreach (string key in toRemoveList)
			{
				cachedFonts.Remove(key);
			}
		}

		/// <summary>
		/// Clears all fonts.
		/// </summary>
		public void ClearFonts()
		{
			cachedFonts.Clear();
		}
		#endregion
	}
}
